<?php declare(strict_types=1);

namespace App\Services\Pay\GuoTonXinYi;


use App\Exceptions\BizException;
use App\Vo\ResultVo;
use Illuminate\Support\Facades\Log;

class Income
{


    public static function addCustGetBeneficiar(array $params, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::addCustGetBeneficiar;
            $reqData = [
                "agetId" => $config["agetId"],
                "busNo" => $params["busNo"] ?? "",
                "timeStamp" => date("YmdHis", time()),
                "version" => Config::VERSION,
            ];
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqData["sign"] = $sign;
            $resultArray = Config::post($url, $reqData);
            Log::channel("income")->info("addCustGetBeneficiar", [
                "url" => $url,
                "req" => $reqData,
                "res" => $resultArray
            ]);
            if ($resultArray["code"] != "000000") {
                throw new BizException($resultArray["msg"]);
            }
            $resultVo = ResultVo::code("ok")::data($resultArray["data"])::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }

    public static function addCustUpdateStatus(array $params, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::addCustUpdateStatus;
            $reqData = [
                "agetId" => $config["agetId"],
                "custId" => $params["mch_no"] ?? "",
                "activeStatus" => $params["status"],
                "operationReason" => $params["operationReason"] ?? "",
                "remark" => $params["remark"] ?? "",
                "timeStamp" => date("YmdHis", time()),
                "version" => Config::VERSION,
            ];
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqData["sign"] = $sign;
            $resultArray = Config::post($url, $reqData);
            if ($resultArray["code"] != "000000") {
                throw new BizException($resultArray["msg"]);
            }
            $resultVo = ResultVo::code("ok")::data($resultArray["data"])::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }


    public static function addCustUploadImg(array $params, string $flag, string $img, array $config): string
    {
        try {
            $url = Config::getDomain() . Config::addCustUploadImg;
            $reqData = [
                "operType" => $params["operType"],
                "custLogin" => $params["custLogin"],
                "agetId" => $config["agetId"],
                "flag" => $flag,
                "version" => Config::VERSION,
            ];
            if ($params["operType"] == "2" && !empty($params["mchNo"])) {
                $reqData["custId"] = $params["mchNo"];
            }
            if (isset($params["timestamp"])) {
                $reqData["timestamp"] = $params["timestamp"];
            }

            $imgBase64 = "";
            if (!empty($img)) {
                $imgBase64 = base64_encode(file_get_contents($img));
            }
            //处理flag
            switch ($flag) {
                case "1":
                    $msg = "身份证正面照片（人像面）";
                    $reqData["credPhotoFront"] = $imgBase64;
                    break;
                case "2":
                    $msg = "身份证正面照片（人像面）";
                    $reqData["credPhotoBack"] = $imgBase64;
                    break;
                case "3":
                    $msg = "结算卡正面照（法人对私与非法人对私上传“结算卡正面照”，对公上传“开户许可证/印鉴卡”）";
                    $reqData["authPic"] = $imgBase64;
                    break;
                case "4":
                    $msg = "营业场所门头照";
                    $reqData["doorHeaderPhoto"] = $imgBase64;
                    break;
                case "5":
                    $msg = "营业场所内景照";
                    $reqData["indoorScenesPhoto"] = $imgBase64;
                    break;
                case "6":
                    $msg = "补充材料①";
                    $reqData["filed1"] = $imgBase64;
                    break;
                case "7":
                    $msg = "补充材料②";
                    $reqData["filed2"] = $imgBase64;
                    break;
                case "8":
                    $msg = "补充资料③";
                    $reqData["filed3"] = $imgBase64;
                    break;
                case "9":
                    $msg = "事业单位证明函照片，政府组织及事业单位进件必传，可前往材料下载板块内下载模板";
                    $reqData["filed4"] = $imgBase64;
                    break;
                case "10":
                    $msg = "补充材料⑤";
                    $reqData["filed5"] = $imgBase64;
                    break;
                case "12":
                    $msg = "营业执照（企业与个体户传营业执照，政府组织及事业单位传事业单位法人证书、其他组织机构传登记证书）";
                    $reqData["busPhotoFront"] = $imgBase64;
                    break;
                case "13":
                    $msg = "非法人对私身份证正面照";
                    $reqData["credPicF"] = $imgBase64;
                    break;
                case "14":
                    $msg = "非法人对私身份证反面照";
                    $reqData["credPicB"] = $imgBase64;
                    break;
                case "15":
                    $msg = "非法人对私上传的授权书";
                    $reqData["authCert"] = $imgBase64;
                    break;
                case "16":
                    $msg = "结算人站门头照（储备字段无需处理）";
                    $reqData["stlDoor"] = $imgBase64;
                    break;
                case "17":
                    $msg = "非法人授权结算书合影（法人或结算人与授权书合影）";
                    $reqData["stlAuth"] = $imgBase64;
                    break;
                case "18":
                    $msg = "收银台照";
                    $reqData["cashierPhoto"] = $imgBase64;
                    break;
                case "19":
                    $msg = "结算人收银台照，小微商户必传";
                    $reqData["jsrcPhoto"] = $imgBase64;
                    break;
                case "33":
                    $msg = "受益人身份证正面照";
                    $reqData["beneficiarCredFront"] = $imgBase64;
                    break;
                case "34":
                    $msg = "受益人身份证反面照";
                    $reqData["beneficiarCredBack"] = $imgBase64;
                    break;
                default:
                    $msg = "flag参数异常";
            }
            if (empty($img)) {
                throw new \Exception($msg . "flag" . $flag . "_图片参数:" . $img);
            }
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqData["sign"] = $sign;
            $resultArray = Config::post($url, $reqData);
            Log::channel("income")->info("addCustUploadImg", [
                "url" => $url,
//                "req" => $reqData,
                "res" => $resultArray
            ]);
            if ($resultArray["code"] != "000000") {
                throw new BizException($resultArray["msg"] . "_错误的图片类型：" . $msg);
            }
//            $resultVo = ResultVo::code("ok")::data(["timestamp" => $resultArray["data"]["timestamp"]])::msg($resultArray["msg"]);
            return (string)$resultArray["data"]["timestamp"];
        } catch (\Exception $e) {
            throw new BizException($e->getMessage());
//            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }

    }


    public static function addCustUpdateCustAccount(array $params, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::addCustUpdateCustAccount;
            $reqData = [
                "agetId" => $config["agetId"],
                "custId" => $params["mchNo"],
                "accountType" => $params["accountType"],
                "timestamp" => $params["timestamp"],
                "accountName" => $params["accountName"],
                "accountNo" => $params["accountNo"],
                "version" => Config::VERSION,
            ];
            if ($params["accountType"] == "01") {
                $reqData["branchName"] = $params["branchName"];
//                $reqData["bankno"] = $params["bankno"];
            } else if ($params["accountType"] == "03") {
                $reqData["stlName"] = $params["stlName"];
                $reqData["accCredNo"] = $params["stlName"];
                $reqData["accCredStartDate"] = $params["stlName"];
                $reqData["accCredEndDate"] = $params["stlName"];
            }
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqDate["sign"] = $sign;
            $resultArray = Config::post($url, $reqDate);
            $resultVo = ResultVo::code("ok")::data($resultArray["data"])::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("error")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }


    public static function addCustUpdateCustRate(array $params, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::addCustUpdateCustRate;
            $reqData = [
                "agetId" => $config["orgId"],
                "custId" => $params["mchNo"],
                "rateWx" => $params["rateWx"],
                "rateWxD" => $params["rateWxD"],
                "rateZfb" => $params["rateZfb"],
                "rateYlCap0" => $params["rateYlCap0"],
                "rateYlCap1" => $params["rateYlCap1"],
                "rateYlRat0" => $params["rateYlRat0"],
                "rateYlRat1" => $params["rateYlRat1"],
                "version" => Config::VERSION,
                "timeStamp" => date("YmdHis", time()),
            ];
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqDate["sign"] = $sign;
            $resultArray = Config::post($url, $reqDate);
            $resultVo = ResultVo::code("ok")::data($resultArray["data"])::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("error")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }

    public static function addCustMiniApply(array $params, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::addCustMiniApply;
            $reqData = [
                "agetId" => $config["agetId"],
                "operType" => $params["operType"],
                "custLogin" => $params["custLogin"],
                "busName" => $params["busName"],
                "manageType" => $params["manageType"],
                "mcccode" => $params["mcccode"],
                "provId" => $params["provId"],
                "cityId" => $params["cityId"],
                "areaId" => $params["areaId"],
                "custAddr" => $params["custAddr"],
                "custName" => $params["custName"],
                "credNo" => $params["credNo"],
                "credStartDate" => self::fmtDate($params["credStartDate"], "身份证有效期开始日期"),
                "credEndDate" => self::fmtDate($params["credEndDate"], "身份证有效期结束日期"),
                "mobileNo" => $params["mobileNo"],
                "accountName" => $params["accountName"],
                "accountNo" => $params["accountNo"],
                "stlType" => $params["stlType"],
                "rateWx" => $params["rateWx"],
                "rateZfb" => $params["rateZfb"],
                "rateYlCap0" => $params["rateYlCap0"],
                "rateYlCap1" => $params["rateYlCap1"],
                "rateYlRat0" => $params["rateYlRat0"],
                "rateYlRat1" => $params["rateYlRat1"],
                "ratePosJy" => $params["ratePosJy"],
                "ratePosJb" => $params["ratePosJb"],
                "ratePosDy" => $params["ratePosDy"],
                "ratePosDb" => $params["ratePosDb"],
                "moneyPosJy" => $params["moneyPosJy"],
                "moneyPosJb" => $params["moneyPosJb"],
                "ratePosM" => $params["ratePosM"],
                "ratePosS" => $params["ratePosS"],
                "custChanType" => "0",
                "refPower" => "1",
                "checkCode" => $params["checkCode"],
                "projectCode" => $params["projectCode"],
                "timestamp" => $params["timestamp"],
                "version" => Config::VERSION,
            ];

            if ($params["operType"] == 2) {
                $reqData["custId"] = $params["mchNo"];
            }
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqData["sign"] = $sign;
            $resultArray = Config::post($url, $reqData);
            Log::channel("income")->info("addCustMiniApply", [
                "url" => $url,
                "req" => $reqData,
                "res" => $resultArray
            ]);
            if ($resultArray["code"] != "000000") {
                throw new BizException($resultArray["msg"]);
            }
            $resultVo = ResultVo::code("ok")::data($resultArray["data"])::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }

    protected static function fmtDate(string $date, string $error): string
    {
        if (empty($date)) {
            throw new BizException($error . "必须填写");
        }
        if ($date == "长期") {
            return $date;
        }
        return date("Ymd", strtotime($date));
    }

    public static function addCustCommonApply(array $params, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::addCustCommonApply;
            $reqData = [
                "agetId" => $config["agetId"],
                "operType" => $params["operType"],
                "custLogin" => $params["custLogin"],
                "busName" => $params["busName"],
                "refName" => $params["refName"],
                "licenseno" => $params["licenseno"],
                "busStartDate" => self::fmtDate($params["busStartDate"], "营业执照有效期开始日期"),
                "busEndDate" => self::fmtDate($params["busEndDate"], "营业执照有效期结束日期"),
                "busType" => $params["busType"],
                "mcccode" => $params["mcccode"],
                "provId" => $params["provId"],
                "cityId" => $params["cityId"],
                "areaId" => $params["areaId"],
                "custAddr" => $params["custAddr"],
                "custName" => $params["custName"],
                "nolegalCertType" => "0",
                "credNo" => $params["credNo"],
                "credStartDate" => self::fmtDate($params["credStartDate"], "法人身份证有效期开始日期"),
                "credEndDate" => self::fmtDate($params["credEndDate"], "法人身份证有效期开始日期"),
                "mobileNo" => $params["mobileNo"],
                "accountName" => $params["accountName"],
                "accountNo" => $params["accountNo"],
                "rateWx" => $params["rateWx"],
                "stlType" => $params["stlType"],
                "rateZfb" => $params["rateZfb"],
                "rateYlCap0" => $params["rateYlCap0"],
                "rateYlCap1" => $params["rateYlCap1"],
                "rateYlRat0" => $params["rateYlRat0"],
                "rateYlRat1" => $params["rateYlRat1"],
                "ratePosJy" => $params["ratePosJy"],
                "ratePosJb" => $params["ratePosJb"],
                "ratePosDy" => $params["ratePosDy"],
                "ratePosDb" => $params["ratePosDb"],
                "moneyPosJy" => $params["moneyPosJy"],
                "moneyPosJb" => $params["moneyPosJb"],
                "ratePosM" => $params["ratePosM"],
                "ratePosS" => $params["ratePosS"],
                "custChanType" => "0",
                "refPower" => "1",
                "checkCode" => $params["checkCode"],
                "projectCode" => $params["projectCode"],
                "timestamp" => $params["timestamp"],
                "version" => Config::VERSION,
                "accountType" => $params["accountType"]
            ];
            if ($params["operType"] == 2) {
                $reqData["custId"] = $params["mchNo"];
            }

            if (isset($reqData["bankno"]) && empty($reqData["bankno"])) {
                throw new BizException("联行号不能为空");
            }

            switch ($params["accountType"]) {
                case "01":
                    $reqData["bankno"] = $params["bankno"];
                    break;
                case "03":
                    $reqData["stlName"] = $params["stlName"];
                    $reqData["accCredType"] = $params["accCredType"];
                    $reqData["accCredNo"] = $params["accCredNo"];
                    $reqData["accCredStartDate"] = self::fmtDate($params["accCredStartDate"], "非法人结算人证件有效期开始时间");
                    $reqData["accCredEndDate"] = self::fmtDate($params["accCredEndDate"], "非法人结算人证件有效期结束时间");
                    break;
            }
            if ($params["busType"] == "2") {
                $reqData["beneficiarName"] = $params["beneficiarName"];
                $reqData["beneficiarStaff"] = $params["beneficiarStaff"];
                $reqData["beneficiarPercent"] = $params["beneficiarPercent"];
                $reqData["beneficiarCredNo"] = $params["beneficiarCredNo"];
                $reqData["beneficiarCertType"] = $params["beneficiarCertType"];
                $reqData["beneficiarAddr"] = $params["beneficiarAddr"];
                $reqData["beneficiarStartTime"] = self::fmtDate($params["beneficiarStartTime"], "受益人证件开始时间");
                $reqData["beneficiarEndTime"] = self::fmtDate($params["beneficiarEndTime"], "受益人证件结束时间");
            }
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqData["sign"] = $sign;
            $resultArray = Config::post($url, $reqData);
            Log::channel("income")->info("addCustMiniApply", [
                "url" => $url,
                "req" => $reqData,
                "res" => $resultArray
            ]);
            if ($resultArray["code"] != "000000") {
                throw new BizException($resultArray["msg"]);
            }
            $resultVo = ResultVo::code("ok")::data($resultArray["data"])::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }


    public static function addCustGetResult(array $params, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::addCustGetResult;
            $reqData = [
                "agetId" => $config["agetId"],
                "authType" => $params["authType"] ?? "0",
                "version" => Config::VERSION
            ];
            $reqData["custId"] = $params["custId"];
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqData["sign"] = $sign;
            Log::channel("income")->info("addCustGetResult", [
                "url" => $url,
                "req" => $reqData,
            ]);
            $resultArray = Config::get($url, $reqData);
            Log::channel("income")->info("addCustGetResult", [
                "url" => $url,
                "res" => $resultArray
            ]);
            if ($resultArray["code"] != "000000") {
                throw new BizException($resultArray["msg"]);
            }
            $resultVo = ResultVo::code("ok")::data($resultArray["data"])::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("failed")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }


    public static function addCustGetCustInfo(array $params, array $config): ResultVo
    {
        try {
            $url = Config::getDomain() . Config::addCustGetCustInfo;
            $reqData = [
                "agetId" => $config["orgId"],
                "custId" => $params["mchNo"],
                "custLogin" => $params["phone"],
                "authType" => $params["authType"] ?? "0",
                "version" => Config::VERSION
            ];
            $sign = Config::getSign($reqData, $config["public_key"]);
            $reqDate["sign"] = $sign;
            $resultArray = Config::post($url, $reqDate);
            $resultVo = ResultVo::code("ok")::data($resultArray["data"])::msg($resultArray["msg"]);
        } catch (\Exception $e) {
            $resultVo = ResultVo::code("error")::data(null)::msg($e->getMessage() . "File:" . $e->getFile() . "Line:" . $e->getLine());
        }
        return $resultVo;
    }
}